﻿using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LittleBee.Utils
{
	public static class CodeCompiler
	{
        public static MemoryStream Compile(string code)
        {
            //var references = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic)
            //	.Select(a => a.Location)
            //	.Distinct()
            //	.Select(l => MetadataReference.CreateFromFile(l))
            //	.ToArray();
            var references = AppDomain.CurrentDomain.GetAssemblies().Select(x => MetadataReference.CreateFromFile(x.Location));

            var cSharpCompilation = CSharpCompilation
                .Create(Guid.NewGuid().ToString() + ".dll")
                .WithOptions(new CSharpCompilationOptions(
                    Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary,
                    usings: null,
                    optimizationLevel: OptimizationLevel.Debug, // TODO
                    checkOverflow: false, // TODO
                    allowUnsafe: true, // TODO
                    platform: Platform.AnyCpu,
                    warningLevel: 4,
                    xmlReferenceResolver: null))
                .AddReferences(references);

            using (var ms = new MemoryStream())
			{
                cSharpCompilation
                    .AddSyntaxTrees(CSharpSyntaxTree.ParseText(code))   // 添加语法树
                    // 生成程序集流
                    // 这里将流导入到内存流中
                    // 如果要生成dll文件，使用 Emit(dllPath)
                    .Emit(ms);
                return ms;
            }
        }

    }
}
